package com.cabrida.livestar.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.model.FansLiveListData;
import com.cabrida.livestar.model.JSONParser;
import com.cabrida.livestar.model.LiveAdvData;
import com.cabrida.livestar.model.StarGiftData;
import com.cabrida.livestar.model.StarMsgData;
import com.cabrida.livestar.pay.PayActivity;
import com.cabrida.livestar.util.DialogShareView;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.MyUtils;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.StringUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUser;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
/**
 * 直播
 * 
 * @author why
 * 
 */
public class FansLiveRoomActivity extends BaseActivity {
	public static final String TAG = FansLiveRoomActivity.class.getSimpleName();
	private TXLivePlayer mLivePlayer;
	private ImageButton ib_back;
	private ImageView iv_header;
	private TextView tv_notice;
	private TextView tv_name;
	private TextView tv_number;
	private String channel;
	private String L_udid;
	private int number=1;
	private ListView listView;
	private FansLiveRoomMsgLvAdapter adapter;
	private FansGiftGvAdapter adapter_gift;

	private ArrayList<StarMsgData> _list = new ArrayList<StarMsgData>();
	private ArrayList<StarGiftData> _list_gift = new ArrayList<StarGiftData>();
	
	private LinearLayout ll_write;
	private LinearLayout ll_btn;
	private LinearLayout ll_list;
	private Button btn_write;
	private Button btn_gift;
	private Button btn_share;

	private EditText et_content;
	private Button btn_send_msg;
	
	private LinearLayout ll_gift;
	private ImageView iv_good;
	private TextView tv_check_good_price;
	private GridView gridView;
	private TextView tv_account_money;
	private ImageButton iv_goto_buy;
	private Button btn_send_gift;
	
	private LinearLayout gift_con;
	private GiftShowManager giftManger;
	
	private String shareTitle="";
	private String shareContent="";
	
	private ArrayList<LiveAdvData> listAdv = new ArrayList<LiveAdvData>();
	
	private ImageView iv_adv1;
	private ImageView iv_adv2;
	private ImageView iv_adv3;
	private ImageView iv_adv4;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_fans_live_room);
		ib_back = (ImageButton) findViewById(R.id.ib_back);
		gift_con = (LinearLayout) findViewById(R.id.gift_con);
		iv_header = (ImageView) findViewById(R.id.iv_header);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_number = (TextView) findViewById(R.id.tv_number);
		listView = (ListView) findViewById(R.id.listView);
		ll_write = (LinearLayout) findViewById(R.id.ll_write);
		ll_btn = (LinearLayout) findViewById(R.id.ll_btn);
		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		btn_write = (Button) findViewById(R.id.btn_write);
		btn_gift = (Button) findViewById(R.id.btn_gift);
		btn_share = (Button) findViewById(R.id.btn_share);
		et_content = (EditText) findViewById(R.id.et_content);
		btn_send_msg = (Button) findViewById(R.id.btn_send_msg);
		ll_gift = (LinearLayout) findViewById(R.id.ll_gift);
		iv_good = (ImageView) findViewById(R.id.iv_good);
		tv_check_good_price = (TextView) findViewById(R.id.tv_check_good_price);
		gridView = (GridView) findViewById(R.id.gridView);
		tv_account_money = (TextView) findViewById(R.id.tv_account_money);
		iv_goto_buy = (ImageButton) findViewById(R.id.iv_goto_buy);
		btn_send_gift = (Button) findViewById(R.id.btn_send_gift);
		tv_notice = (TextView) findViewById(R.id.tv_notice);
		iv_adv1 = (ImageView) findViewById(R.id.iv_adv1);
		iv_adv2 = (ImageView) findViewById(R.id.iv_adv2);
		iv_adv3 = (ImageView) findViewById(R.id.iv_adv3);
		iv_adv4 = (ImageView) findViewById(R.id.iv_adv4);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		ib_back.setOnClickListener(this);
		btn_write.setOnClickListener(this);
		btn_send_msg.setOnClickListener(this);
		btn_gift.setOnClickListener(this);
		iv_goto_buy.setOnClickListener(this);
		btn_send_gift.setOnClickListener(this);
		btn_share.setOnClickListener(this);
		iv_adv1.setOnClickListener(this);
		iv_adv2.setOnClickListener(this);
		iv_adv3.setOnClickListener(this);
		iv_adv4.setOnClickListener(this);

		ll_write.setVisibility(View.INVISIBLE);
		ll_btn.setVisibility(View.VISIBLE);
		adapter = new FansLiveRoomMsgLvAdapter(context);
		listView.setAdapter(adapter);
		adapter_gift = new FansGiftGvAdapter(context);
		gridView.setAdapter(adapter_gift);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				StarGiftData data = (StarGiftData) arg0.getAdapter().getItem(arg2);
				for (int i = 0; i < _list_gift.size(); i++) {
					if (arg2==i) {
						_list_gift.get(i).setIscheck(true);
					}else{
						_list_gift.get(i).setIscheck(false);
					}
						
				}
				adapter_gift.notifyDataSetChanged();
			}
		});

		// mPlayerView即step1中添加的界面view
		TXCloudVideoView mPlayerView = (TXCloudVideoView) findViewById(R.id.video_view);
		// 创建player对象
		mLivePlayer = new TXLivePlayer(context);
		// 关键player对象与界面view
		mLivePlayer.setPlayerView(mPlayerView);
		mPlayerView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ll_write.setVisibility(View.INVISIBLE);
				ll_btn.setVisibility(View.VISIBLE);
				ll_list.setVisibility(View.VISIBLE);
				ll_gift.setVisibility(View.INVISIBLE);
			}
		});
		mLivePlayer.setPlayListener(new ITXLivePlayListener() {
			
			@Override
			public void onPlayEvent(int arg0, Bundle arg1) {
				// TODO Auto-generated method stub
				L.e(TAG, "setPlayListener", "arg0");
				if (arg0==-2301) {
					dialogQuit();
				}
			}
			
			@Override
			public void onNetStatus(Bundle arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		FansLiveListData data = (FansLiveListData) getIntent().getSerializableExtra("data");
		channel =  data.getL_channel();
		L_udid =  data.getL_udid();
		MyUtils.loadImg(data.getU_avatar(), iv_header);
		tv_name.setText(data.getS_name());
		if (StringUtils.isBlank(data.getL_click())) {
			number = 1;
		}else{
			number = Integer.valueOf(data.getL_click())+1;
		}
		tv_number.setText(number+"在线");
		InRoom();
		giftManger = new GiftShowManager(context, gift_con);
		giftManger.showGift();// 开始显示礼物
	}
	
	
	private void dialogQuit(){
		new AlertDialog.Builder(context).setTitle("温馨提示")//设置对话框标题  
		
		  .setMessage("直播已结束！")//设置显示的内容  
		
		   .setPositiveButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮  
	 
		       
	
	      @Override  
	
      public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件  
	
           // TODO Auto-generated method stub  
		
	    	  LeaveRoom();
	
	        }  
		
		    }).show();//在按键响应事件中显示此对话框  

	}

	TIMUser user;
	
	private void getIMMsg(String response){
		StarMsgData data = new StarMsgData();
		try {
			JSONObject obj = new JSONObject(response);
			if (!StringUtils.isBlank(obj.optString("userAction"))) {
				data.setUserAction(obj.optInt("userAction"));
			}
			if (!StringUtils.isBlank(obj.optString("nickName"))) {
				data.setNickName(obj.optString("nickName"));
			}
			if (!StringUtils.isBlank(obj.optString("userId"))) {
				data.setUserId(obj.optString("userId"));
			}
			if (!StringUtils.isBlank(obj.optString("headPic"))) {
				data.setHeadPic(obj.optString("headPic"));
			}
			String userAction = JsonUtils.getString(response, "userAction", "0");
			int ua = Integer.valueOf(userAction);
			if (Global.AVIMCMD_Fans_Present==ua) {
				if (!StringUtils.isBlank(obj.optString("msg"))) {
					if (obj.optString("msg").contains(",")) {
						String[] aaStrings = obj.optString("msg").split(",");
					data.setMsg(aaStrings[0]);
				}
				}
			}else{
				if (!StringUtils.isBlank(obj.optString("msg"))) {
					data.setMsg(obj.optString("msg"));
				}
			}
				
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		_list.add(data);
		adapter.setData(_list);
		adapter.notifyDataSetChanged();
		listView.setSelection(_list.size());
	}
	
	/** 获取观看头像列表 */
	private void LiveUserData() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("suid", L_udid);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_LIVEINFO_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "LiveUserData", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							JSONObject share = JsonUtils.getJSONObject(data, "share", new JSONObject());
							JSONArray mall = JsonUtils.getJSONArray(data, "mall", new JSONArray());
							listAdv = JSONParser.getLiveAdvList(mall);
							shareTitle = JsonUtils.getString(share, "title", "");
							shareContent = JsonUtils.getString(share, "content", "");
							if (null== listAdv||listAdv.size()==0||listAdv.size()!=4) {
								iv_adv1.setVisibility(View.GONE);
								iv_adv2.setVisibility(View.GONE);
								iv_adv3.setVisibility(View.GONE);
								iv_adv4.setVisibility(View.GONE);
							}else {
								MyUtils.loadImg(listAdv.get(0).getImg(), iv_adv1);
								MyUtils.loadImg(listAdv.get(1).getImg(), iv_adv2);
								MyUtils.loadImg(listAdv.get(2).getImg(), iv_adv3);
								MyUtils.loadImg(listAdv.get(3).getImg(), iv_adv4);
							}
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 获取礼物列表 */
	private void getGiftList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("type", Global.U_type);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_GIFT_LIST_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "get_gift_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							JSONArray list = JsonUtils.getJSONArray(data,
									"list", new JSONArray());
							String u_balance = JsonUtils.getString(data,
									"u_balance", "");
							tv_account_money.setText(u_balance);
							_list_gift = JSONParser.getFansGiftList(list);
							if (_list_gift != null && _list_gift.size() > 0) {
								ll_gift.setVisibility(View.VISIBLE);
								ll_btn.setVisibility(View.INVISIBLE);
								ll_list.setVisibility(View.INVISIBLE);
								setGiftListData();
							} else {
								showToast("暂无礼物");
							}
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	private void setGiftListData() {
		_list_gift.get(0).setIscheck(true);
		adapter_gift.setData(_list_gift);
		adapter_gift.notifyDataSetChanged();
	}

	private void OpenIm() {
		user = new TIMUser();
		user.setAccountType(Global.IMSDK_ACCOUNT_TYPE + "");
		user.setAppIdAt3rd(Global.IMSDK_APPID + "");
		user.setIdentifier(Global.U_id);
		//初始化SDK基本配置
		TIMSdkConfig config = new TIMSdkConfig(Global.IMSDK_APPID);
		
		config .enableCrashReport(false);
		config  .enableLogPrint(true);
		        config.setLogLevel(TIMLogLevel.DEBUG);

		//初始化SDK
		TIMManager.getInstance().init(getApplicationContext(), config);
		
		// identifier为用户名，userSig 为用户登录凭证
		TIMManager.getInstance().login(Global.U_id, Global.TIm_Sig, new TIMCallBack() {

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				TIMGroupManager.getInstance().applyJoinGroup(channel, "some reason", new TIMCallBack() {
		    	    @java.lang.Override
		    	    public void onError(int code, String desc) {
		    	        //接口返回了错误码code和错误描述desc，可用于原因
		    	        //错误码code列表请参见错误码表
		    	        Log.e(TAG, "disconnected");
		    	    }

		    	    @java.lang.Override
		    	    public void onSuccess() {
		    	        Log.i(TAG, "join group");
		    	        sendMsg(Global.AVIMCMD_Custom_EnterLive, "进入房间");
		    	    }
		    	});
			}});
		TIMManager.getInstance().addMessageListener(new TIMMessageListener() {

			@Override
			public boolean onNewMessages(List<TIMMessage> list) {
				// TODO Auto-generated method stub
				if (null==list||list.size()==0) {
					return false;
				}
				TIMMessage msg = list.get(0);
				TIMElem timelem = msg.getElement(0);
				if (timelem.getType() == TIMElemType.GroupSystem) {

				} else {
					TIMTextElem elem = (TIMTextElem) msg.getElement(0);
					String text = elem.getText();
					getIMMsg(text);
					String userAction = JsonUtils.getString(text, "userAction", "0");
					int ua = Integer.valueOf(userAction);
					if (Global.AVIMCMD_Custom_EnterLive==ua) {
						number++;
						tv_number.setText(number+"在线");
					}
					if (Global.AVIMCMD_Star_ExitLive==ua) {
						showToast("主播已经关闭直播");
						LeaveRoom();
					}
					if (Global.AVIMCMD_Fans_Present==ua) {
						String message = JsonUtils.getString(text, "msg", "");
						if (message.contains(",")) {
							String[] aaStrings = message.split(",");
							String giftPos = aaStrings[1];
							GiftVo vo = new GiftVo();
							String nickName = JsonUtils.getString(text, "nickName", "");
							String headPic = JsonUtils.getString(text, "headPic", "");
							vo.setName(nickName);
							vo.setSendheader(headPic);
							vo.setNum(1);
							vo.setGiftName("花");
							vo.setImg(giftPos);
							giftManger.addGift(vo);
						}
					}
				}

				return false;
			}
		});
	}

	/** 进入房间 */
	private void InRoom() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("suid", L_udid);
		params.put("status", 1);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_ENTER_ROOM_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "enterroom_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							
							
							
							JSONArray url = JsonUtils.getJSONArray(data, "url",
									new JSONArray());
							String data_flv = JSONParser.getInLiveRomm(url);
							mLivePlayer.startPlay(data_flv,
									TXLivePlayer.PLAY_TYPE_LIVE_FLV); // 推荐FLV
							String msg=JsonUtils.getString(data,"msg", "");
							tv_notice.setText(msg);
							OpenIm();
							LiveUserData();
							// mLivePlayer.setPlayListener(new
							// ITXLivePlayListener() {
							//
							// @Override
							// public void onPlayEvent(int arg0, Bundle arg1) {
							// // TODO Auto-generated method stub
							//
							// }
							//
							// @Override
							// public void onNetStatus(Bundle arg0) {
							// // TODO Auto-generated method stub
							//
							// }
							// });
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	/** 离开房间 */
	private void LeaveRoom() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("status", 3);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_LEAVE_ROOM_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "leaveroom_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							mLivePlayer.pause();
							finish();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
							mLivePlayer.pause();
							finish();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
						mLivePlayer.pause();
						finish();
					}
				});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	private void sendMsg(int userAction,String content){
		// 构造一条消息
		TIMMessage msg = new TIMMessage();

		// 添加文本内容
		TIMTextElem elem = new TIMTextElem();
		
		try {
			JSONObject obj = new JSONObject();
			obj.put("userAction",userAction );
			obj.put("nickName", Global.U_nickname);
			obj.put("userId", Global.U_id);
			obj.put("headPic", Global.headPic);
			obj.put("msg", content);
			obj.put("level", "1");
//			obj.put("level", Global.U_lv);
			elem.setText(obj.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		// 将elem添加到消息
		if (msg.addElement(elem) != 0) {
			L.e(TAG, "addElement---", "addElement failed");
			return;
		}

		// 获取群聊会话
		TIMConversation conversation = TIMManager.getInstance()
				.getConversation(TIMConversationType.Group, // 会话类型：群组
						channel);
		// 发送消息
		conversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {// 发送消息回调
					@Override
					public void onError(int code, String desc) {// 发送消息失败
						// 错误码code和错误描述desc，可用于定位请求失败原因
						// 错误码code含义请参见错误码表
						L.e(TAG, "send message failed. code: ---", code
								+ " errmsg: " + desc);
//						showToast("发送失败，请重新尝试！");
					}

					@Override
					public void onSuccess(TIMMessage msg) {// 发送消息成功
						L.e(TAG, "SendMsg ok.  ---", "");
						showToast("发送成功！");
						et_content.setText("");
						ll_btn.setVisibility(View.VISIBLE);
						ll_write.setVisibility(View.INVISIBLE);

						TIMTextElem elem = (TIMTextElem) msg.getElement(0);
						getIMMsg(elem.getText());
					}
				});
	}
	
	private Dialog dialogExit;
	public void popExitWindows() {
		showExitDialog();
	}

	private void showExitDialog() {
		initExitDialogView();
		if (null != dialogExit && dialogExit.isShowing()) {
			return;
		}
		if (null != dialogExit) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialogExit.getWindow();
			// 设置显示动画
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = ((Activity) context).getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
			// 设置显示位置
			dialogExit.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialogExit.setCanceledOnTouchOutside(true);
			dialogExit.show();
		}
	}

	private void initExitDialogView() {
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_quit, null);
		TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
		tv_title.setText("主播已关闭直播");
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setVisibility(View.GONE);
		Button btn_sure = (Button) view.findViewById(R.id.btn_sure);
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != dialogExit) {
					dialogExit.dismiss();
					LeaveRoom();
				}
			}
		});

		dialogExit = new Dialog(context, R.style.dialogWindowStyle);
		dialogExit.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogExit.setContentView(view, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
	
	/** 发送礼物 */
	private void sendGift(String cid,final int pos) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("cid", cid);
		params.put("suid", L_udid);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_GIFT_FANS_SEND_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "send_gift_response", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							sendMsg(Global.AVIMCMD_Fans_Present, message+","+pos);
							ll_gift.setVisibility(View.INVISIBLE);
							ll_list.setVisibility(View.VISIBLE);
							ll_btn.setVisibility(View.VISIBLE);
								String giftPos = pos+"";
								GiftVo vo = new GiftVo();
								vo.setName(Global.U_nickname);
								vo.setSendheader(Global.headPic);
								vo.setNum(1);
								vo.setGiftName("花");
								vo.setImg(giftPos);
								giftManger.addGift(vo);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		LeaveRoom();
		super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.ib_back:
			LeaveRoom();
			break;
		case R.id.btn_share:
			DialogShareView dsv = new DialogShareView(context);
//			http://192.168.1.111:8081/Share/Lives?channel=14963879508861
			String urlString  = Urls.SHARE_URL+"Share/Lives?channel="+channel;
			dsv.initLiveDialog(urlString,shareTitle,shareContent);
			break;
		case R.id.btn_gift:
			getGiftList();
			ll_gift.setVisibility(View.VISIBLE);
			ll_list.setVisibility(View.INVISIBLE);
			ll_btn.setVisibility(View.INVISIBLE);
			break;
		case R.id.iv_goto_buy:
			ll_gift.setVisibility(View.INVISIBLE);
			ll_list.setVisibility(View.VISIBLE);
			ll_btn.setVisibility(View.VISIBLE);
			openActivity(PayActivity.class);
			break;
		case R.id.btn_send_gift:
			String gid = "";
			int pos=0;
			for (int i = 0; i < _list_gift.size(); i++) {
				if (_list_gift.get(i).isIscheck()) {
					gid = _list_gift.get(i).getG_id();
					pos = i;
				}
			}
			sendGift(gid,pos);
			break;
		case R.id.btn_write:
			ll_btn.setVisibility(View.INVISIBLE);
			ll_write.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_send_msg:
			String content = et_content.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				showToast("发送内容不能为空！");
				break;
			}
			sendMsg(Global.AVIMCMD_Custom_Text,content);
			break;
		case R.id.iv_adv1:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(0).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv2:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(1).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv3:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(2).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		case R.id.iv_adv4:
		{
			Bundle b = new Bundle();
			b.putString("url", listAdv.get(3).getUrl());
			openActivity(FansWebActivity.class, b);
		}
			break;
		default:
			break;
		}
	}

}
